package org.lakeside.outreach.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class AddProjectPopupPanel extends Widget implements ClickHandler {

	PopupPanel outer = new PopupPanel();
	VerticalPanel inner = new VerticalPanel();
	HTML heading = new HTML("<h6>Create New Project</h6>");
	FlexTable table = new FlexTable();
	TextBox nameTextBox = new TextBox();
	TextArea descriptionTextBox = new TextArea();
	Button saveButton = new Button("Save");
	Button cancelButton = new Button("Cancel");
	
	public AddProjectPopupPanel() {		
		// construct form
		table.setText(0, 0, "Project Title: ");
		table.setWidget(0, 1, nameTextBox);
		table.setText(1, 0, "Description: ");
		table.setWidget(1, 1, descriptionTextBox);
		table.setWidget(2, 1, cancelButton);
		table.setWidget(2, 2, saveButton);
		table.setWidth("100%");
		
		inner.add(heading);
		inner.add(table);
		
		outer.add(inner);
		
		// listen for clicks on save button
		saveButton.addClickHandler(this);
		
		// listen for clicks on cancel button
		cancelButton.addClickHandler(this);
	}
	
	private void add() {
		ProjectServiceAsync projectService = GWT.create(ProjectService.class);
		projectService.addProject(nameTextBox.getText(), descriptionTextBox.getText(),
				new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(Void result) {
						reload();
						hide();
					}
		});
	}
	
	private void cancel() {
		nameTextBox.setText("");
		descriptionTextBox.setText("");
		hide();
	}
	
	public void hide() {
		outer.hide();
	}
	
	public void reload() {
		OutreachManager.get().getProjectList().loadProjects();
	}
	
	public void show() {
		outer.show();
		outer.center();
	}

	@Override
	public void onClick(ClickEvent event) {
		Object source = event.getSource();
		if(source == saveButton) {
			add();
		} else {
			cancel();
		}
	}
}
